package cn.iune.web.security.shiro;

import java.text.MessageFormat;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.config.Ini;
import org.apache.shiro.config.Ini.Section;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.FactoryBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;

import cn.iune.backcenter.author.sysinfo.ISysActionService;
import cn.iune.backcenter.author.sysinfo.SysAction;
import cn.iune.backcenter.author.sysinfo.SysInfo;
import cn.iune.system.config.SysInfoCache;

public class ChainDefinitionSectionMetaSource implements FactoryBean<Ini.Section> {

	
	/**
	 * 默认premission字符串
	 */
	public static final String ROLE_STRING = "roles[\"{0}\"]";
	public static final String PREMISSION_STRING = "perms[\"{0}\"]";

//	@Autowired
//	private ISysInfoService sysInfoService;
	@Autowired
	@Lazy
	private ISysActionService sysActionService;
	@Autowired
	@Lazy
	private SysInfoCache sysInfoCache;
	

	/**
	 * 通过filterChainDefinitions对默认的url过滤定义
	 * 
	 * @param filterChainDefinitions
	 *            默认的url过滤定义
	 */
	
	private String filterChainDefinitions;
	
	public void setFilterChainDefinitions(String filterChainDefinitions) {
		this.filterChainDefinitions = filterChainDefinitions;
		System.out.println("ChainDefinitionSectionMetaSource-->>setFilterChainDefinitions()被调用");
	}
	
	
	@Override
	public Section getObject() throws BeansException {
		// TODO Auto-generated method stub

		System.out.println("ChainDefinitionSectionMetaSource-->>开始读取shiro的静态权限配置清单......");
		Ini ini = new Ini();
		// 加载默认的url(spring-shiro.xml配置文件中配置的静态数据)
		ini.load(filterChainDefinitions);
		Ini.Section section = ini.getSection(Ini.DEFAULT_SECTION_NAME);
		System.out.println("ChainDefinitionSectionMetaSource-->>完成读取shiro的静态权限配置清单......");
		
		
//		System.out.println("开始打印shiro标配的静态权限配置清单......");
//		for(Map.Entry<String, String> entry : section.entrySet()){
//			System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue());  
//		}
		
//		Ini.Section section = null;
		System.out.println("ChainDefinitionSectionMetaSource-->>开始读取shiro的动态权限配置清单......");
		
//		List<SaOppermission> list = saOppermissionUtil.getAll();
//		List<SysInfo> list = sysInfoService.getAll();
//		String appId = AppConfigParams.APPID;
		
//		System.out.println("ChainDefinitionSectionMetaSource-->>appId-->>"+appId);
//		List<SysInfo> list = sysInfoService.getPagList(appId);

		//这里需要加载全部应用的所有预设权限，供shiro判断是否当前用户具有权限
//		sysInfoCache = SpringUtils.getBean(SysInfoCache.class);
//		List<SysInfo> list = sysInfoService.getPagList();
		List<SysInfo> list = sysInfoCache.getPagList();
		
//		JSONArray jsonArray = AppSystemService.getJSONArrayByList(list);
		//存入预装载对象中
		//写入AppPreloading
//		appPreloading.setSysInfoPags(jsonArray);
		
//		List<SysInfo> list = AppSystemService.getListByArray(SysInfo.class, appPreloading.getSysInfoPags().toJSONString());
		
		
		System.out.println("ChainDefinitionSectionMetaSource-->>标配数量：-->>"+list.size());
//		for(SaOppermission saOppermission : list){
		for(SysInfo sysInfoPag : list){
			// 如果不为空值添加到section中
			//将角色ID作为角色name
//			if (!CommonService.isEmptyString(saOppermission.getsProcess()) && !CommonService.isEmptyString(saOppermission.getsProcess())) {
//				section.put(saOppermission.getsProcess(), MessageFormat.format(ROLE_STRING, saOppermission.getsProcess()));
//			}
			if (/*"pag".equals(sysInfoPag.getSystemKind()) && */StringUtils.isNotEmpty(sysInfoPag.getAbsoluteUrl())) {
//				System.out.println("标配："+sysInfoPag.getSystemFullName());
				//读取角色
				section.put(sysInfoPag.getAbsoluteUrl(), MessageFormat.format(ROLE_STRING, sysInfoPag.getAbsoluteUrl()));
				//获取权限列表
				String systemFullID = sysInfoPag.getSystemFullID();
//				sysActionService = SpringUtils.getBean(ISysActionService.class);
				List<SysAction> listAction = sysActionService.getBySystemFullID(systemFullID);
        		for(SysAction sysAction : listAction){
        			String action = sysAction.getActionCode();
        			String permission = sysInfoPag.getAbsoluteUrl() + ":" + action;
        			String url = sysInfoPag.getAbsoluteUrl() + "/" + action;
    				section.put(url, MessageFormat.format(PREMISSION_STRING, permission));
        		}
				
				/*
				List<SysInfo> list1 = sysInfoUtil.getChilds(sysInfoPag.getfID());
        		for(SysInfo sysInfoAct : list1){
        			String action = sysInfoAct.getAbsoluteUrl();
//        			String permission = saOppermission.getsPermissionRoleID() + ":" + action;
        			String permission = sysInfoPag.getAbsoluteUrl() + ":" + action;
        			String url = sysInfoPag.getAbsoluteUrl() + "/" + action;
    				section.put(url, MessageFormat.format(PREMISSION_STRING, permission));
        		}
        		*/
				
			}
			
			//读取权限数据
			/*
        	String actions  = saOppermission.getsActions();
        	if(null!=actions && !"".equals(actions)){
        		//处理权限
        		JSONArray actionsArray = JSON.parseArray(actions);
//        		System.out.println("actionsArray-->"+actionsArray);
        		for(int i=0;i<actionsArray.size();i++){
        			String action = (String) actionsArray.getJSONObject(i).get("name");
//        			String permission = saOppermission.getsPermissionRoleID() + ":" + action;
        			String permission = saOppermission.getsProcess() + ":" + action;
        			String url = saOppermission.getsProcess() + "/" + action;
    				section.put(url, MessageFormat.format(PREMISSION_STRING, permission));
        		}
        	}
        	*/
			
		}
		
//		Map<String,String> map = chainDefinitionSectionMetaSource.getObject();
		/*
		 * System.out.println("开始打印shiro标配的动态权限配置清单......"); for(Map.Entry<String,
		 * String> entry : section.entrySet()){ System.out.println("Key = " +
		 * entry.getKey() + ", Value = " + entry.getValue()); }
		 */
		
		/*
		// 获取所有Resource
		List<Resource> list = resourceDao.getAll();

		// 循环Resource的url,逐个添加到section中。section就是filterChainDefinitionMap,
		// 里面的键就是链接URL,值就是存在什么条件才能访问该链接
		for (Iterator<Resource> it = list.iterator(); it.hasNext();) {

			Resource resource = it.next();
			// 如果不为空值添加到section中
			if (StringUtils.isNotEmpty(resource.getValue()) && StringUtils.isNotEmpty(resource.getPermission())) {
				section.put(resource.getValue(), MessageFormat.format(PREMISSION_STRING, resource.getPermission()));
			}

		}
		*/
		System.out.println("ChainDefinitionSectionMetaSource-->>完成读取shiro的动态权限配置清单......");

		return section;

	}

	@Override
	public Class<?> getObjectType() {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public boolean isSingleton() {
		// TODO Auto-generated method stub
		return false;
	}
	

}
